<template>
  <div>

    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.licensePlate" clearable placeholder="车牌号" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
        <!-- ✅ 导入导出按钮 -->
        <!-- <el-button
          type="success"
          icon="el-icon-upload2"
          class="mr10"
          @click="$refs.excelInput.click()"
        >导入 Excel</el-button> -->
        <input
          type="file"
          ref="excelInput"
          style="display: none"
          accept=".xlsx, .xls"
          @change="importFromExcel"
        />
        <el-button
          type="warning"
          icon="el-icon-download"
          @click="handleExport"
        >导出 Excel</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <!-- <el-table-column prop="vehicleId" label="车辆标识"></el-table-column> -->
        <el-table-column prop="licensePlate" label="车牌号"></el-table-column>
        <el-table-column prop="vehicleType" label="车辆类型"></el-table-column>
        <el-table-column prop="capacity" label="载客量"></el-table-column>
        <el-table-column prop="driverName" label="司机姓名"></el-table-column>
        <el-table-column prop="driverPhone" label="司机手机号"></el-table-column>
        <el-table-column prop="notes" label="备注"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.vehicleId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />
        </el-form-item>

        <el-form-item label="车辆类型" prop="vehicleType">
          <el-input v-model="form.vehicleType" placeholder="请输入车辆类型" />
        </el-form-item>

        <el-form-item label="载客量" prop="capacity">
          <el-input v-model.number="form.capacity" placeholder="请输入载客量" />
        </el-form-item>

        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="form.driverName" placeholder="请输入司机姓名" />
        </el-form-item>

        <el-form-item label="司机手机号" prop="driverPhone">
          <el-input v-model="form.driverPhone" placeholder="请输入司机手机号" />
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="form.notes" placeholder="请输入备注" />
        </el-form-item>

      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="30%">
      <el-form
        ref="form"
        :model="addForm"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="addForm.licensePlate" placeholder="请输入车牌号" />
        </el-form-item>
      
        <el-form-item label="车辆类型" prop="vehicleType">
          <el-input v-model="addForm.vehicleType" placeholder="请输入车辆类型" />
        </el-form-item>
      
        <el-form-item label="载客量" prop="capacity">
          <el-input-number v-model="addForm.capacity" :min="1" placeholder="请输入载客量" style="width: 100%;" />
        </el-form-item>
      
        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="addForm.driverName" placeholder="请输入司机姓名" />
        </el-form-item>
      
        <el-form-item label="联系电话" prop="driverPhone">
          <el-input v-model="addForm.driverPhone" placeholder="请输入联系电话" />
        </el-form-item>
      
        <el-form-item label="备注" >
          <el-input
            type="textarea"
            v-model="addForm.notes"
            placeholder="请输入备注"
            rows="3"
          />
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'
import dayjs from 'dayjs';


export default {
    name: 'basetable',
    data() {
      return {
        query: {
            licensePlate: '',
            pageIndex: 1,
            pageSize: 30
        },
        tableData: [],
        multipleSelection: [],
        exportData: [],
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        form: {
          vehicleId: '',
          licensePlate: '',
          vehicleType: '',
          capacity: null,
          driverName: '',
          driverPhone: '',
          notes: ''
        },
        hotels:{},
        users:{},
        addForm: {
          vehicleId: '',
          licensePlate: '',
          vehicleType: '',
          capacity: null,
          driverName: '',
          driverPhone: '',
          notes: ''
        },
        idx: -1,
        id: -1,
        rules: {
          licensePlate: [
            { required: true, message: '请输入车牌号', trigger: 'blur' },
            {
              pattern: /^[\u4e00-\u9fa5][A-Z][A-Z0-9]{5}$/,
              message: '请输入有效的车牌号（如 粤B12345）',
              trigger: 'blur'
            }
          ],
          vehicleType: [
            { required: true, message: '请输入车辆类型', trigger: 'blur' }
          ],
          capacity: [
            { required: true, message: '请输入载客量', trigger: 'blur' },
            {
              type: 'number',
              min: 1,
              message: '载客量必须为正整数',
              trigger: 'blur'
            }
          ],
          driverName: [
            { required: true, message: '请输入司机姓名', trigger: 'blur' }
          ],
          driverPhone: [
            { required: true, message: '请输入司机手机号', trigger: 'blur' },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入有效的手机号码',
              trigger: 'blur'
            }
          ],
          notes: [
            { required: true, message: '请输入备注', trigger: 'blur' }
          ]
        }
      };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/vehicles/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          licensePlate: this.query.licensePlate
        }).then(res=>{
          this.pageTotal = res.total,
          this.tableData = res.data
        });
      },
      // 触发搜索按钮
      handleSearch() {
          this.loading();
      },
      // 删除操作
      handleDelete(row) {
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
        })
            .then(() => {
                requests.delete("/vehicles/delById",{
                  vehicleId: row
                }).then(res=>{
                  this.$message.success(res);
                  this.loading()
                })
            })
      },
      // 编辑操作
      handleEdit(row) {
        // 安全深拷贝 row 对象，避免响应式污染
        const newForm = JSON.parse(JSON.stringify(row));
        // 赋值给表单
        this.form = newForm;
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.form.resetFields();
      },
      // 保存编辑
      saveEdit() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          // 校验成功，调用接口
          requests.post("/vehicles/edit", this.form)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.editVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
        // 单选、多选改变时调用
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的酒店');
          return;
        }
      
        this.$confirm(`确定删除这 ${this.multipleSelection.length} 项吗？`, '提示', {
          type: 'warning'
        })
          .then(() => {
            const ids = this.multipleSelection.map(item => item.vehicleId);
            requests.post('/vehicles/delByIds', ids)  // ✅ 注意这里直接传数组
              .then(res => {
                this.$message.success(res);
                this.loading(); // 重新加载表格
              })
          })
      },
      //新增操作
      handleAdd(row) {
        this.addForm = row;
        this.addVisible = true;
      },
      // 取消操作
      cancelAdd() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.addForm.resetFields();
      },
      // 保存操作
      saveAdd() {
        // 先校验表单
        this.$refs.form.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
        
          // 校验成功，调用接口
          requests.post("/vehicles/add", this.addForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.addVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      // 通用：监听酒店名称变更
      handleHotelChange(hotelName, targetForm = this.form) {
        const selected = this.hotels.find(h => h.hotelName === hotelName);
        if (selected) {
          targetForm.hotels.hotelId = selected.hotelId;
          targetForm.hotelId = selected.hotelId;
        } else {
          targetForm.hotels.hotelId = '';
          targetForm.hotelId = '';
        }
      },
      // 通用：监听参会者名称变更
      handleParticipantChange(fullName, targetForm = this.form) {
        const selected = this.users.find(user => user.fullName === fullName);
        if (selected) {
          targetForm.participants.participantId = selected.participantId;
          targetForm.participantId = selected.participantId;
        } else {
          targetForm.participants.participantId = '';
          targetForm.participantId = '';
        }
      },
      //导出
      handleExport() {
        requests.get("/vehicles/exportVehicleInfor").then(res => {
          // 转换导出数据格式
          let exportData = res.map(row => {
            return {
              // 车辆标识: String(row.vehicleId || ''),
              车牌号: row.licensePlate || '',
              车辆类型: row.vehicleType || '',
              载客量: row.capacity != null ? String(row.capacity) : '',
              司机姓名: row.driverName || '',
              司机手机号: row.driverPhone || '',
              备注: row.notes || ''
            };
          });
        
          // 保证表头存在，即使没有数据
          if (exportData.length === 0) {
            exportData.push({
              // 车辆标识: '',
              车牌号: '',
              车辆类型: '',
              载客量: '',
              司机姓名: '',
              司机手机号: '',
              备注: ''
            });
          }
        
          // 创建工作表
          const ws = XLSX.utils.json_to_sheet(exportData);
        
          // 设置列宽
          ws['!cols'] = [
            // { wch: 12 }, // 车辆标识
            { wch: 15 }, // 车牌号
            { wch: 15 }, // 车辆类型
            { wch: 10 }, // 载客量
            { wch: 15 }, // 司机姓名
            { wch: 20 }, // 司机手机号
            { wch: 50 }  // 备注
          ];
        
          // 设置“车辆标识”为文本格式
          const header = Object.keys(exportData[0]);
          const keys = Object.keys(ws);
          const idIndex = header.indexOf('车辆标识');
          if (idIndex >= 0) {
            const colLetter = String.fromCharCode(65 + idIndex);
            keys.forEach(key => {
              if (key.startsWith(colLetter) && key !== `${colLetter}1`) {
                const cell = ws[key];
                if (cell) {
                  cell.t = 's';
                  cell.z = '@';
                }
              }
            });
          }
        
          // 导出 Excel 文件
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '车辆信息');
          XLSX.writeFile(wb, '车辆信息列表.xlsx');
        })
      },
      //导入
      importFromExcel(e) {
        const file = e.target.files[0];
        if (!file) return;
      
        const reader = new FileReader();
        reader.onload = (event) => {
          const data = new Uint8Array(event.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
        
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
        
          // 读取为 JSON 数组（跳过全空行）
          let excelData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
          excelData = excelData.filter(row => {
            return Object.values(row).some(v => v != null && String(v).trim() !== '');
          });
        
          if (!excelData || excelData.length === 0) {
            this.$message.warning('Excel 中无有效数据，无法导入');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 映射字段
          const mappedData = excelData.map((row, idx) => {
            const vehicleId = Number(row['车辆标识']);
            const capacity = Number(row['载客量']);
          
            if (isNaN(vehicleId)) {
              console.warn(`第 ${idx + 2} 行车辆标识无效，跳过`, row);
              return null;
            }
          
            return {
              vehicleId: isNaN(vehicleId) ? null : vehicleId,
              licensePlate: row['车牌号'] || '',
              vehicleType: row['车辆类型'] || '',
              capacity: isNaN(capacity) ? null : capacity,
              driverName: row['司机姓名'] || '',
              driverPhone: row['司机手机号'] || '',
              notes: row['备注'] || ''
            };
          }).filter(item => item !== null);
        
          if (mappedData.length === 0) {
            this.$message.warning('所有行均不符合导入要求，未生成可提交的数据');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 提交到后端
          requests.post('/vehicles/importVehicleInfor', mappedData)
            .then(response => {
              this.$message.success(response);
              this.loading();
            })
          this.$refs.excelInput.value = '';
        };
      
        reader.readAsArrayBuffer(file);
      }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
